/*
 * File     : StringParameter.java
 * Created  : 22 Apr 2011
 *
 * Copyright © 2011 Matthew Wilson (mj. {my-surname} .uk {at} gmail.com)
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Lesser General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */
package com.googlecode.dni.internal.call;

import static com.googlecode.dni.internal.DniTypes.FAST_CHARSET_TYPE;
import static org.objectweb.asm.Opcodes.*;

import java.util.Map;

import org.objectweb.asm.ClassWriter;
import org.objectweb.asm.MethodVisitor;

import com.googlecode.dni.internal.string.FastCharset;


/**
 * <p>
 *  Encapsulates a parameter to a native call that comes from a Java
 *  {@link String}.
 * </p>
 *
 * @author Matthew Wilson
 */
final class StringParameter extends Parameter
{

    private String fieldName;

    private final FastCharset fastCharset;

    private boolean writeFastCharsetField;


    /**
     * @param fastCharset
     *            the fast charset
     */
    StringParameter( final FastCharset fastCharset )
    {
        this.fastCharset = fastCharset;

        StringBuilder str = new StringBuilder( "FAST_CHARSET" );
        for ( int i = 0; i < fastCharset.getName().length(); i++ )
        {
            char c = fastCharset.getName().charAt( i );
            if ( Character.isJavaIdentifierPart( c ) )
            {
                str.append( c );
            }
            else
            {
                str.append( '_' );
            }
        }
        this.fieldName = str.toString();

        setNativeTypeAsPointer();
    }

    /**
     * {@inheritDoc}
     */
    @Override
    int getJavaVarSlots()
    {
        return 1;
    }

    /**
     * {@inheritDoc}
     */
    @Override
    void allocateFields( final ClassWriter classWriter, final Map< String, Parameter > createdFields )
    {
        if ( createdFields.containsKey( this.fieldName ) )
        {
            assert createdFields.get( this.fieldName ) instanceof StringParameter;
            assert ( (StringParameter) createdFields.get( this.fieldName ) ).fastCharset == this.fastCharset;
            return;
        }

        this.writeFastCharsetField = true;

        createdFields.put( this.fieldName, this );

        classWriter.visitField( ACC_STATIC | ACC_PRIVATE | ACC_FINAL,
                                this.fieldName,
                                "L" + FAST_CHARSET_TYPE + ";",
                                null,
                                null );
    }

    /**
     * {@inheritDoc}
     */
    @Override
    void writeStaticInitialiserFragment( final MethodVisitor methodVisitor )
    {
        if ( this.writeFastCharsetField )
        {
            methodVisitor.visitLdcInsn( this.fastCharset.getName() );
            methodVisitor.visitMethodInsn( INVOKESTATIC,
                                           FAST_CHARSET_TYPE,
                                           "getInstance",
                                           "(Ljava/lang/String;)L" + FAST_CHARSET_TYPE + ";" );
            methodVisitor.visitFieldInsn( PUTSTATIC,
                                          getLibraryImplName(),
                                          this.fieldName,
                                          "L" + FAST_CHARSET_TYPE + ";" );
        }
    }

    /**
     * {@inheritDoc}
     */
    @Override
    boolean needsScratchMemory()
    {
        return true;
    }

    /**
     * {@inheritDoc}
     */
    @Override
    void writeScratchMemorySize( final MethodVisitor methodVisitor )
    {
        if ( this.fastCharset.getStaticClassName() != null )
        {
            methodVisitor.visitVarInsn( ALOAD, getJavaVarIndex() );

            methodVisitor.visitMethodInsn( INVOKESTATIC,
                                           this.fastCharset.getStaticClassName(),
                                           "getByteCount",
                                           "(Ljava/lang/String;)I" );
        }
        else
        {
            methodVisitor.visitFieldInsn( GETSTATIC,
                                          getLibraryImplName(),
                                          this.fieldName,
                                          "L" + FAST_CHARSET_TYPE + ";" );
            methodVisitor.visitVarInsn( ALOAD, getJavaVarIndex() );

            methodVisitor.visitMethodInsn( INVOKEVIRTUAL,
                                           FAST_CHARSET_TYPE,
                                           "getByteCount",
                                           "(Ljava/lang/String;)I" );
        }
    }

    /**
     * {@inheritDoc}
     */
    @Override
    void writePrepareParameter( final MethodVisitor methodVisitor )
    {
        if ( this.fastCharset.getStaticClassName() == null )
        {
            methodVisitor.visitFieldInsn( GETSTATIC,
                                          getLibraryImplName(),
                                          this.fieldName,
                                          "L" + FAST_CHARSET_TYPE + ";" );
        }
        methodVisitor.visitVarInsn( ALOAD, getJavaVarIndex() );
        writeGetScratchBuffer();

        if ( this.fastCharset.getStaticClassName() != null )
        {
            methodVisitor.visitMethodInsn( INVOKESTATIC,
                                           this.fastCharset.getStaticClassName(),
                                           "encode",
                                           "(Ljava/lang/String;Ljava/nio/ByteBuffer;)V" );
        }
        else
        {
            methodVisitor.visitMethodInsn( INVOKEVIRTUAL,
                                           FAST_CHARSET_TYPE,
                                           "encode",
                                           "(Ljava/lang/String;Ljava/nio/ByteBuffer;)V" );
        }
    }

    /**
     * {@inheritDoc}
     */
    @Override
    void writeGetParameter( final MethodVisitor methodVisitor )
    {
        writeGetScratchPointer();
    }

    /**
     * {@inheritDoc}
     */
    @Override
    void writeReturnParameter( final MethodVisitor methodVisitor,
                               final int returnVarIndex )
    {
        writeGetReturnResult( methodVisitor, returnVarIndex );

        if ( getNativeType() == 'I' )
        {
            methodVisitor.visitInsn( I2L );
            methodVisitor.visitLdcInsn( 0xffffffffL );
            methodVisitor.visitInsn( LAND );
        }

        methodVisitor.visitMethodInsn( INVOKESTATIC,
                                       this.fastCharset.getStaticClassName(),
                                       "decode",
                                       "(J)Ljava/lang/String;" );

        methodVisitor.visitInsn( ARETURN );

//        // TODO code shared with NativeStringParameter (which is not yet written)
//
//        writeAddressToNullablePointer( methodVisitor, returnVarIndex, true );
//
//        // TODO sounds like a shared string pool would be nice for a library if desired...
//        // but would have to implement deletion from string pool too!
//        methodVisitor.visitMethodInsn( INVOKESTATIC,
//                                       STRING_POOL_TYPE,
//                                       "wrap",
//                                       "(L" + POINTER_TYPE + ";)L" + NATIVE_STRING_TYPE + ";" );
//
//        // TODO correct charset
//        methodVisitor.visitLdcInsn( "##default##" );
//        methodVisitor.visitMethodInsn( INVOKEINTERFACE,
//                                       NATIVE_STRING_TYPE,
//                                       "read",
//                                       "(Ljava/lang/String;)Ljava/lang/String;" );
//
//        methodVisitor.visitInsn( ARETURN );
    }

}
